<template>
  <div class="app-container" v-loading="loading.getPageList">
    <div>
      <el-button type="primary" size="normal" @click="save">保存</el-button>
      <el-button type="primary" size="normal" @click="getConfigs()">
        刷新
      </el-button>
      <el-button type="primary" size="normal" @click="loadPlugins()">
        载入插件（初次使用需要载入插件）
      </el-button>
    </div>
    <br />
    <editPanel ref="editPanelRef"></editPanel>
  </div>
</template>

<script setup>
import { ref, nextTick } from "vue";
import editPanel from "../components/PluginConfigs/EditPanel.vue";
import { usePluginConfigStore } from "../stores/pluginConfig";

const loading = ref({ getPageList: false });
const pluginConfigStore = usePluginConfigStore();
const editPanelRef = ref(null);

const save = () => {
  loading.value.getPageList = true;

  pluginConfigStore
    .addOrUpdateConfig(editPanelRef.value.getControls())
    .then((res) => {
      loading.value.getPageList = false;
      this.getConfigs();
    })
    .catch((e) => {
      loading.value.getPageList = false;
    });
};
const getConfigs = async () => {
  loading.value.getPageList = true;
  pluginConfigStore
    .getPluginApplyConfigs()
    .then((res) => {
      loading.value.getPageList = false;
      if (res && res.configs && res.configs.length > 0) {
        nextTick(() => {
          editPanelRef.value.setControls(res);
        });
      } else {
        //无数据尝试载入插件
        loadPlugins(isFirst);
      }
    })
    .catch((e) => {
      loading.value.getPageList = false;
    });
};
const loadPlugins =(isFirst) => {
  loading.value.getPageList = true;
  pluginConfigStore
    .loadPlugins()
    .then((res) => {
      loading.value.getPageList = false;
      if (res && res.configs) {
        nextTick(() => {
          editPanelRef.value.setControls(res);
          if(isFirst){
            this.getConfigs();
          }
        });
      }
    })
    .catch((e) => {
      loading.value.getPageList = false;
    });
};

nextTick(() => {
  getConfigs();
});
</script>

<style lang="scss"></style>
